/*
 * (C) 2012	Sheng Yi
 * another way to implement dup2
 * limit: donot use fcntl
 */
#include "apue.h"
#define	LENGTH	4096

int mydup2(int filedes, int filedes2);

int main(int argc, char* argv[])
{
	int fd, newfd;
	if (argc != 2)
		err_quit("usage: a.out <new descriptor>");
	fd = atoi(argv[1]);
	printf("new fd is %d\n", fd);

	newfd = mydup2(0, fd);
	if (fd == newfd)
		printf("open fd success!\n");
	else
		printf("open fd fail!\n");

	return 0;
}

int mydup2(int filedes, int filedes2)
{
	int fds[LENGTH] = {-1};
	int fd,pos = -1;

	if (filedes < 0 || filedes2 < 0)
		err_quit("ilegal file descriptor");
	if (filedes == filedes2)
		return filedes;

	close(filedes2);
	while ((fd = dup(filedes)) != filedes2)
		fds[++pos] = fd;

	/* close the file descriptors that open above */
	while (pos >= 0)
		close(fds[pos--]);

	return fd;
}
